package com.hjx.windowtool.util;

import java.awt.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.JTextField;

public class StrUtil {
	public static final String DATE_PATTERN = "yyyy-MM-dd";
	public static final String TIME_PATTERN = "HH:mm:ss";
	public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public static final String SERIAL_PATTERN = "yyyyMMddHHmmss";

	public static String formatDate(Date date, String pattern) {
		if(date == null){
			return "";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	public static Date parseDate(String dateStr){
		return parse(dateStr, DATE_PATTERN);
	}

	public static Date parseDateTime(String dateStr){
		return parse(dateStr,DATETIME_PATTERN);
	}

	public static Date parse(String dateStr,String pattern){
		SimpleDateFormat sdf = new SimpleDateFormat(pattern.trim());
		try {
			return sdf.parse(dateStr.trim());
		} catch (Exception e) {
			return null;
		}
	}

	public static String formatDateTime(Date date) {
		return formatDate(date, DATETIME_PATTERN);
	}

	public static String formatDate(Date date) {
		return formatDate(date, DATE_PATTERN);
	}

    public static String formatTime(Date date) {
        return formatDate(date, TIME_PATTERN);
    }

	public static boolean isEmpty(String s) {
		return s == null || s.trim().length() == 0;
	}

	public static boolean isEmpty(byte[] obj) {
		return obj == null || obj.length == 0;
	}

	@SuppressWarnings("rawtypes")
	public static boolean isEmpty(Map m) {
		return m == null || m.isEmpty();
	}

    public static boolean isEmpty(Object o) {
        return o == null;
    }

    public static boolean isEmpty(Object[] obj) {
		return obj == null || obj.length == 0;
	}

    @SuppressWarnings("rawtypes")
	public static boolean isEmpty(Collection s) {
        return s == null || s.isEmpty();
    }

    @SuppressWarnings("rawtypes")
	public static boolean isNotEmpty(Collection s) {
        return !isEmpty(s);
    }

    public static boolean isNotEmpty(Object[] obj) {
        return !isEmpty(obj);
    }
	/**
	 * 分钟字符转换成微秒
	 * 
	 * @param sStart
	 *            mm:ss 格式
	 * @return
	 */
	public static long minuteStringToMicrosecond(String sStart) {
		String[] split = sStart.split(":");
		long time = 0;
		time += Integer.valueOf(split[0]) * 60 * 1000000;
		time += Integer.valueOf(split[1]) * 1000000;
		return time;
	}

	public static Object readObject(String name) {
		File file = new File("temp\\" + name);
		if (!file.exists()) {
			return null;
		}
		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
			return ois.readObject();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}

	public static void saveObject(String name, Object o) {
		try {
			File file = new File("temp\\" + name);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(o);
			oos.flush();
			oos.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	public static File selectToOpen(Component parent) {
		JFileChooser jf = new JFileChooser();
		jf.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		if (parent instanceof JTextField) {
			String text = ((JTextField) parent).getText();
			if (!isEmpty(text)) {
				jf.setSelectedFile(new File(text));
			}
		}
		int showOpenDialog = jf.showOpenDialog(jf);
		if (showOpenDialog == 0) {
			return jf.getSelectedFile();
		}
		return null;
	}

	/**
	 * "file:/home/whf/cn/fh" -> "/home/whf/cn/fh" "jar:file:/home/whf/foo.jar!cn/fh" ->
	 * "/home/whf/foo.jar"
	 */
	public static String getRootPath(URL url) {
		String fileUrl = url.getFile();
		int pos = fileUrl.indexOf('!');

		if (-1 == pos) {
			return fileUrl;
		}

		return fileUrl.substring(5, pos);
	}

	/**
	 * "cn.fh.lightning" -> "cn/fh/lightning"
	 * 
	 * @param name
	 * @return
	 */
	public static String dotToSplash(String name) {
		return name.replaceAll("\\.", "/");
	}

	/**
	 * "Apple.class" -> "Apple"
	 */
	public static String trimExtension(String name) {
		int pos = name.indexOf('.');
		if (-1 != pos) {
			return name.substring(0, pos);
		}

		return name;
	}

	/**
	 * /application/home -> /home
	 * 
	 * @param uri
	 * @return
	 */
	public static String trimURI(String uri) {
		String trimmed = uri.substring(1);
		int splashIndex = trimmed.indexOf('/');

		return trimmed.substring(splashIndex);
	}
	
	/**
	 * 根据属性名获取属性值
	 * */
    public static Object getFieldValueByName(String fieldName, Object o) {
        try {
        	if (o instanceof Map) {
				@SuppressWarnings("rawtypes")
				Map m=(Map) o;
				return m.get(fieldName);
			}
//        	Field field = o.getClass().getDeclaredField(fieldName);
//        	Object value = field.get(o);
            String firstLetter = fieldName.substring(0, 1).toUpperCase();  
            String getter = "get" + firstLetter + fieldName.substring(1);  
            Method method = o.getClass().getMethod(getter, new Class[] {});  
            Object value = method.invoke(o, new Object[] {});  
            return value;  
        } catch (Exception e) {  
            e.printStackTrace();
            return null;  
        }  
    }
    
    public static void copy(Object src, Object target) {
		Class<? extends Object> class1 = target.getClass();
		Method[] methods = class1.getMethods();
		Class<? extends Object> class2 = src.getClass();
		//TODO 用了后不知道为什么服务器不能启动
//		Map<String, Method> map = Stream.of(class2.getMethods()).filter(t->t.getName().startsWith("get")&&t.getParameterCount()==0).collect(Collectors.toMap(Method::getName, t -> t));
		
		Map<String, Method> map=new HashMap<>();
		for (Method t : class2.getMethods()) {
			if (t.getName().startsWith("get")&&t.getParameterCount()==0) {
				map.put(t.getName(), t);
			}
		}
		for (Method method : methods) {
			String name = method.getName();
			if (method.getParameterCount()!=1||!name.startsWith("set")) {
				continue;
			}
			try {
				Method method2 = map.get("get"+name.substring(3));
				if (method2==null) {
					continue;
				}
				method.invoke(target, method2.invoke(src));
			} catch (Exception e) {
				
			}
		}
		
	}

}
